$(document).ready(function(){
    var flag = false;
    var getParam = function(key) {
        var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) {
            return r[2];
        } else {
            return null;
        }
    };
    var getData = function() {
        console.log(decodeURI(getParam('data')))
        return JSON.parse(decodeURI(getParam('data')));
    };
    var viewportTemplate; // the viewport template
    loadTemplate("templates/viewport_moblie.html", function(element) {

    // loadTemplate("templates/viewport.html", function(element) {
        viewportTemplate = element;
        if(flag) {
            func(getData());
        }
        flag = true;
    });

    var studyViewerTemplate; // the study viewer template
    loadTemplate("templates/studyViewer.html", function(element) {
        studyViewerTemplate = element;
        if(flag) {
            func(getData());

        }
        flag = true;
    });

    var myDatatable;
    var myurl = GetHosturl();
    getDatatable();

    function getDatatable() {
        try{


            console.log(myurl);
            myDatatable = $('#studydatatable').DataTable({
                language: {
                    url: "//cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/Chinese.json"
                },
                paging: true,
                lengthChange: false, //设置每页显示
                searching: true,
                ordering: true,
                bSort: true, //排序功能
                info: true,
                autoWidth: false,
                //"aaSorting": [[2, "desc"]], //设置排序列 2，为第三列desc或是asc,表示升序或者降序
                //"scrollY": 400,
                scrollCollapse: true, //当显示更少的记录时，是否允许表格减少高度
                selectRows: true,
                info: true,			//左下角信息
                paging: true,		//设置本地翻页
                //"processing": true,
                serverSide: false,
                ajax: function (data, callback) {
                    //封装请求参数
                    /* var param = {};
                     param.limit = data.length;//页面显示记录条数，在页面显示每页显示多少项的时候
                     param.start = data.start;//开始的记录序号
                     param.page = (data.start / data.length)+1;//当前页码*/
                    //console.log(param);
                    //ajax请求数据
                    $.ajax({
                        type: "POST",
                        //url: "http://120.25.244.147:8081/test/Query/Study",
                        url: myurl +'test/Query/Study',
                        cache: false, //禁用缓存
                        dataType: "json",
                        success: function (result) {
                            console.log('resultresultresultresult',result)
                            var returnData = {};
                            returnData.data = result;//返回的数据列表

                            callback(returnData);

                        }
                    });
                },
                //列表表头字段
                columnDefs: [
                    {visible: false, "targets": [0]}
                ],
                order: [
                    [1, "asc"]
                    //			                [1, "asc"],
                    //			                [2, "desc"],
                ],
                columns: [
                    {"data": "_id"},
                    {"data": "PatientID",render: function( data, type, full, meta ) {
                        if(data){
                            return data;
                        }
                        return '';
                    }},
                    {"data": "PatientName",render: function( data, type, full, meta ) {
                        if(data){
                            return data;
                        }
                        return '';
                    }},
                    {"data": "PatientSex",render: function( data, type, full, meta ) {
                        if(data){
                            return data;
                        }
                        return '';
                    }},
                    {"data": "PatientAge",render: function( data, type, full, meta ) {
                        if(data){
                            return data;
                        }
                        return '';
                    }},
                    {"data": "Modality",render: function( data, type, full, meta ) {
                        if(data){
                            return data;
                        }
                        return '';
                    }},
                    {"data": "StudyDate",render: function( data, type, full, meta ) {
                        if(data){
                            return data;
                        }
                        return '';
                    }},
                    {"data": "BodyPart",render: function( data, type, full, meta ) {
                        if(data){
                            return data;
                        }
                        return '';
                    }},
                    {"data": "StudyDescription",render: function( data, type, full, meta ) {
                        if(data){
                            return data;
                        }
                        return '';
                    }},
                    {"data": "Series.length",render: function( data, type, full, meta ) {
                        if(data){
                            return data;
                        }
                        return '';
                    }},
                    {"data": "CreateTime",render: function( data, type, full, meta ) {
                        if(data){
                            return data;
                        }
                        return '';
                    }},
                    {"data": "Source",render: function( data, type, full, meta ) {
                        if(data){
                            return data;
                        }
                        return '';
                    }},
                    {"data": "UploadDept",render: function( data, type, full, meta ) {
                        if(data){
                            return data;
                        }
                        return '';
                    }},
                    {"data": "UploadUserName",render: function( data, type, full, meta ) {
                        if(data){
                            return data;
                        }
                        return '';
                    }}
                ]
            });
        }
        catch (ex){

        }


    }
    $('#btnquery').click(function () {

        //此处需调用api()方法,否则返回的是JQuery对象而不是DataTables的API对象

        var dttable = $('#studydatatable').dataTable();
        dttable.fnClearTable(); //清空一下table
        dttable.fnDestroy(); //还原初始化了的datatable
        getDatatable();


    })
    var func = function (data) {
        if ($(this).hasClass('selected')) {
            //$(this).removeClass('selected');
        }
        else {
            myDatatable.$('tr.selected').removeClass('selected');
            $(this).addClass('selected');
        }
    if(!data) {
        var data = {
            "_id": "5979e31530c2f315b4fbe422",
            "PatientName": "Wang Weiliang",
            "PatientID": "02288",
            "PatientSex": "M",
            "PatientBirthDate": "19550609",
            "PatientAge": "051Y",
            "Modality": "MR",
            "StudyInstanceUID": "1.3.12.2.1107.5.2.30.25733.30000006060900103396800000022",
            "StudyID": "1", "StudyDescription": "c-spine^general",
            "StudyDate": "20060609",
            "BodyPart": "CSPINE",
            "AccessionNumber": "37012",
            "Source": "湖北人民医院", "UploadDept": "放射科",
            "UploadUserName": "曾诚",
            "UploadUserID": "002",
            "__v": 0,
            "Series": [
                {
                    "SeriesDate": "20060609",
                    "SeriesDescription": "t2_tse_sag_rst_448",
                    "SeriesInstanceUID": "1.3.12.2.1107.5.2.30.25733.30000006060900112162500000565",
                    "SeriesNumber": "2",
                    "Instances": [
                        {
                            Columns: "448",
                            ImageOrientationPatient: "-1.89455238e-011\1\-2.04226554e-010\-0.0923705417292\-2.05103433e-010\-0.9957247024257",
                            ImagePositionPatient: "-9.2807134191739\-139.99999997129\143.8171392535",
                            InstanceNumber: "1",
                            MD5: "75a122e57b607768c5cf790585b9fec8",
                            PixelSpacing: "11824",
                            Rows: "448",
                            SOPInstanceUID: "1.3.12.2.1107.5.2.30.25733.30000006060900112162500000566",
                            WindowCenter: "355",
                            WindowWidth: "754",
                        }
                    ]
                }
            ]
        }
    }
        // alert(JSON.stringify(data))
        console.log('data',data)
        var study = data;
        console.log(data);
        var id =data.PatientID;
        var name = data.PatientName;
        var uri = data._id;
        var closable = 1;
        var  item ={'id':id,'name':name,'url':uri,'closable':closable==1?true:false};
        // closableTab.addTab(item);//干掉tab
        console.log('studyViewerTemplate',studyViewerTemplate)
        // Add tab content by making a copy of the studyViewerTemplate element
        var studyViewerCopy = studyViewerTemplate.clone();

        /*var viewportCopy = viewportTemplate.clone();
         studyViewerCopy.find('.imageViewer').append(viewportCopy);*/


        studyViewerCopy.attr("id", 'tab_container_' + data.PatientID);
        // Make the viewer visible
        studyViewerCopy.removeClass('hidden');
        // Add section to the tab content
        studyViewerCopy.appendTo('#tabContent');

        // Show the new tab (which will be the last one since it was just added
        // $('#tabs a:last').tab('show');

        // Toggle window resize (?)
        $('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
            $(window).trigger('resize');
        });
        // Now load the study.json
        //console.log('studyid:'+data[0]._id);
        loadStudy(studyViewerCopy, viewportTemplate, data);
    }
    //列表选择
    $('#studydatatable tbody').on( 'click', 'tr', function () {
        alert('---')
        if ($(this).hasClass('selected')) {
            //$(this).removeClass('selected');
        }
        else {
            myDatatable.$('tr.selected').removeClass('selected');
            $(this).addClass('selected');
        }
        var data = myDatatable.rows('.selected').data();

        console.log('data[0]',data[0])

        var study = data[0];
        //console.log(study);
        var id =data[0].PatientID;
        var name = data[0].PatientName;
        var uri = data[0]._id;
        var closable = 1;
        var  item ={'id':id,'name':name,'url':uri,'closable':closable==1?true:false};
        closableTab.addTab(item);
        console.log('studyViewerTemplate',studyViewerTemplate)
        // Add tab content by making a copy of the studyViewerTemplate element
        var studyViewerCopy = studyViewerTemplate.clone();

        /*var viewportCopy = viewportTemplate.clone();
         studyViewerCopy.find('.imageViewer').append(viewportCopy);*/


        studyViewerCopy.attr("id", 'tab_container_' + data[0].PatientID);
        // Make the viewer visible
        studyViewerCopy.removeClass('hidden');
        // Add section to the tab content
        studyViewerCopy.appendTo('#tabContent');

        // Show the new tab (which will be the last one since it was just added
        $('#tabs a:last').tab('show');

        // Toggle window resize (?)
        $('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
            $(window).trigger('resize');
        });
        // Now load the study.json
        //console.log('studyid:'+data[0]._id);
        loadStudy(studyViewerCopy, viewportTemplate, data[0]._id);
    })

    $('#btnupload').on( 'click', function () {
        BootstrapDialog.show({
            size:BootstrapDialog.SIZE_SMALL,
            type:BootstrapDialog.TYPE_DEFAULT,
            title: '请选择图像路径',
            message: $('<div class="wwwwlDialogdiv" ><label>选择Dicom图像:</label><input name="inputFile" id="inputFile"  multiple="multiple"   type="file"/></div><div><label id="backlabel"></label></div> </div>'),
            buttons: [ {
                label: '确定',
                // no title as it is optional
                cssClass: 'btn-primary',
                hotkey: 13,
                action: function(dialogItself){
                    var $inputFile=$("#inputFile").get(0); //DOM对象
                    var oFiles = $inputFile.files;
                    // 遍历图片文件列表，插入到表单数据中
                    for (var i = 0, file; file = oFiles[i]; i++) {
                        //console.log(file.name);
                        //console.log(file);
                        var $formDataNew = new FormData();
                        $formDataNew.append("inputFile", file);

                        $.ajax({
                            //url: 'http://120.25.244.147:8081/test/file/uploading' ,
                            url: myurl + 'test/file/uploading' ,
                            type: 'POST',
                            data: $formDataNew,
                            async: false,
                            cache: false,
                            contentType: false,
                            processData: false,
                            success: function (returndata) {
                                //$('backlabel').text(returndata);
                                //console.log(returndata);
                            },
                            error: function (returndata) {
                                console.log(returndata);
                            }
                        });
                    }
                    dialogItself.close();
                }
            },  {
                label: '取消',
                action: function(dialogItself){
                    dialogItself.close();
                }
            }]
        });
    })


    // Show tabs on click
    $('#tabs a').click (function(e) {
        e.preventDefault();
        $(this).tab('show');
    });

// Resize main
    function resizeMain() {
        var height = $(window).height();
        $('#main').height(height - 50);
        $('#tabContent').height(height - 50 - 42);
    }


// Call resize main on window resize
    $(window).resize(function() {
        resizeMain();
    });
    resizeMain();
})